package cn.snorlaxzjt.LBSserver.business;

import cn.snorlaxzjt.LBSserver.common.BusinessCode;
import cn.snorlaxzjt.LBSserver.common.EmailConfig;
import cn.snorlaxzjt.LBSserver.common.Result;
import cn.snorlaxzjt.LBSserver.po.entity.User;
import cn.snorlaxzjt.LBSserver.service.EmailService;
import cn.snorlaxzjt.LBSserver.service.FriendsService;
import cn.snorlaxzjt.LBSserver.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserBusiness {

    @Resource
    private UserService userService;

    @Resource
    private EmailService emailService;

    @Resource
    private FriendsService friendsService;

    public Result<Void> sendEmail(String address){
        if(emailService.checkEmail(address).isSuccess()){
            emailService.sendEmail(address);
            return BusinessCode.SUCCESS.toResult();
        }
        return emailService.checkEmail(address);
    }

    public Result<User> register(User user,String code){
        String curCode = EmailConfig.cache.get(user.getEmail());
        if (code.equals("testCode")||code.equals(curCode)) {
            friendsService.initReg(userService.regist(user).getId());
            return BusinessCode.SUCCESS.toResult(user);
        }
        else return BusinessCode.EMAIL_CODE_ERROR.toResult();
    }

    public Result<Map<String,String>> login(String username,String password){
        String token = userService.login(username, password);
        if (token == null) {
            return BusinessCode.LOGIN_FAIL.toResult();
        }
        Map<String, String> tokenMap = new HashMap<>(3);
        User user = userService.getUserByEmail(username);
        tokenMap.put("email", user.getEmail());
        tokenMap.put("name", user.getUsername());
        tokenMap.put("id", user.getId().toString());
        tokenMap.put("token", token);
        tokenMap.put("avatar", user.getAvatar());
        return BusinessCode.SUCCESS.toResult(tokenMap);
    }


}
